#include "cachetaskparamssetdialog.h"
#include "ui_cachetaskparamssetdialog.h"

#include <QFile>
#include <QTextStream>

CacheTaskParamsSetDialog::CacheTaskParamsSetDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CacheTaskParamsSetDialog)
{
    ui->setupUi(this);

    m_cacheTaskTypeGroup.addButton(ui->checkBox_ramCache, 1);
    m_cacheTaskTypeGroup.addButton(ui->checkBox_diskCache, 2);

    ui->pushButton_start->setEnabled(false);

    connect(&m_cacheTaskTypeGroup,SIGNAL(buttonClicked(int)), this, SLOT(btnGroupTempLevel_slot(int)));
}

CacheTaskParamsSetDialog::~CacheTaskParamsSetDialog()
{
    delete ui;
}

void CacheTaskParamsSetDialog::btnGroupTempLevel_slot(int index)
{
    ui->pushButton_start->setEnabled(true);
}

void CacheTaskParamsSetDialog::cacheTaskParamsSetDigShow_slot(QList<Block_Info> *pSelectList, QList<Block_Info> *pDiskList)
{
    m_pDiskList = pDiskList;
    m_pBlockList = pSelectList;
    qDebug("%s m_pBlockList->size()=%d", __func__, m_pBlockList->size());
    qDebug("%s m_pBlockList->at(0).m_size=%s", __func__,
           m_pBlockList->at(0).m_size.toLocal8Bit().data());
    qDebug("%s pDiskList->size()=%d", __func__, pDiskList->size());

    m_cacheTaskInfo.m_blockInfo = m_pBlockList->at(0);
    m_cacheTaskInfo.m_blockInfo.m_name = QString("/dev/")+m_cacheTaskInfo.m_blockInfo.m_name;

    comboBoxDisks_init();

    setModal(true);
    show();
}

void CacheTaskParamsSetDialog::comboBoxDisks_init()
{
    QList<Block_Info>::iterator it;
    uint i=0;
    for (it=m_pDiskList->begin(); it<m_pDiskList->end();it++)
    {
        Block_Info info = *it;
        ui->comboBox_disks->addItem(info.m_name, i);
        i++;
    }
}

void CacheTaskParamsSetDialog::on_pushButton_start_clicked()
{
    if (ui->checkBox_ramCache->checkState() == Qt::Checked)
    {
        ramCacheTask_set();
    }
    else if (ui->checkBox_diskCache->checkState() == Qt::Checked)
    {
        diskCacheTask_set();
    }
    emit cacheTaskStartOk_signal(&m_cacheTaskInfo);
    hide();
}

void CacheTaskParamsSetDialog::ramCacheTask_set()
{
    m_cacheTaskInfo.m_cacheType = L1_CACHE;
    m_cacheTaskInfo.m_cacheName = "/dev/tram0";

    bool check1=false;
    m_cacheTaskInfo.m_cacheSize = ui->comboBox_memorySize->currentText().toUInt(&check1);
    if (!check1)
        return;

    bool check2=false;
    m_cacheTaskInfo.m_granularitySize = ui->comboBox_granularitySize->currentText().toUInt(&check2);
    if (!check2)
        return;

    int32 strategy_index = ui->comboBox_cacheStrategy->currentIndex();
    if (strategy_index<=1)
    {
       m_cacheTaskInfo.m_cacheStrategyType = static_cast<Cache_Strategy_Type>(strategy_index);
    }
    else
    {
        m_cacheTaskInfo.m_cacheStrategyType = CACHE_READ;
    }

    /*//first step create ram disk
    QString create_ram_disk = QString("%1%2").arg(CMD_CREATE_RAM_DISK)
                              .arg(QString::number(m_cacheTaskInfo.m_cacheSize*1024));
    emit  shellProcessCmdWrite_signal(create_ram_disk, this);

    m_ramDisk = "/dev/ram0";
    //second step modify /etc/init.d/flashcache
    flashCacheFile_modify();

    //third step start flashcache
    QString start_flashcache = CMD_FLASH_CACHE_START;
    emit shellProcessCmdWrite_signal(start_flashcache, this);*/

    m_cacheTaskInfo.m_taskIndex = SystemParams::cacheIdUsedArrayEmpty_get();
    m_cacheTaskInfo.m_taskName=QString::fromUtf8("任务_")+QString::number(m_cacheTaskInfo.m_taskIndex);
    //m_cacheTaskInfo.m_taskUuid="1bab066d 100d6456 6af15086 437f5b1a 5";
    m_cacheTaskInfo.m_taskUuid=SystemParams::cacheTaskUuid_generate();
}

void CacheTaskParamsSetDialog::diskCacheTask_set()
{
    m_cacheTaskInfo.m_cacheType = L2_CACHE;
    m_cacheTaskInfo.m_cacheName = QString("/dev/")+m_diskSelected.m_name;
    m_cacheTaskInfo.m_cacheSize = 0;
    m_cacheTaskInfo.m_diskCacheSize = m_diskSelected.m_size;

    bool check1=false;
    m_cacheTaskInfo.m_granularitySize = ui->comboBox_granularitySize->currentText().toUInt(&check1);
    if (!check1)
        return;

    int32 strategy_index = ui->comboBox_cacheStrategy->currentIndex();
    if (strategy_index<=1)
    {
       m_cacheTaskInfo.m_cacheStrategyType = static_cast<Cache_Strategy_Type>(strategy_index);
    }
    else
    {
        m_cacheTaskInfo.m_cacheStrategyType = CACHE_READ;
    }

    //m_cacheTaskInfo.m_taskName=QString::fromUtf8("任务2");
    //m_cacheTaskInfo.m_taskUuid="1bab066d100d64566af15086437f5b1a6";

    m_cacheTaskInfo.m_taskIndex = SystemParams::cacheIdUsedArrayEmpty_get();
    m_cacheTaskInfo.m_taskName=QString::fromUtf8("任务_")+QString::number(m_cacheTaskInfo.m_taskIndex);
    m_cacheTaskInfo.m_taskUuid=SystemParams::cacheTaskUuid_generate();
}

void CacheTaskParamsSetDialog::flashCacheFile_modify()
{
    QString str_all;
    QStringList str_list;
    QFile read_file("/etc/init.d/flashcache");

    if (read_file.open((QIODevice::ReadOnly|QIODevice::Text)))
    {
        QTextStream stream(&read_file);
        str_all=stream.readAll();
    }
    read_file.close();

    QFile write_file("/etc/init.d/flashcache");
    if(write_file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        qDebug("%s flashcache open is ok", __func__);
        QTextStream stream(&write_file);
        QStringList str_list=str_all.split("\n");

        for (int32 i=0;i<str_list.count();i++)
        {
            if (i==str_list.count()-1)
            {
                //最后一行不需要换行
                stream<<str_list.at(i);
            }
            else
            {
                stream<<str_list.at(i)<<'\n';
            }

            if (str_list.at(i).contains("SSD_DISK=("))
            {
                QString tempStr=str_list.at(i+1);
                tempStr.replace(0, tempStr.length(), m_ramDisk);
                stream<<tempStr<<'\n';
                i+=1;
            }
            else if (str_list.at(i).contains("BLOCK_SIZE=("))
            {
                QString tempStr=str_list.at(i+1);
                tempStr.replace(0, tempStr.length(),
                                QString::number(m_cacheTaskInfo.m_granularitySize)+QString("K"));
                stream<<tempStr<<'\n';
                i+=1;
            }
            else if (str_list.at(i).contains("CACHE_MODE=("))
            {
                QString cache_mode="thru";
                if (m_cacheTaskInfo.m_cacheStrategyType==CACHE_READ)
                {
                    cache_mode="thru";
                }
                else if (m_cacheTaskInfo.m_cacheStrategyType==CACHE_READ_WRITE)
                {
                    cache_mode="back";
                }

                QString tempStr=str_list.at(i+1);
                tempStr.replace(0, tempStr.length(),cache_mode);
                stream<<tempStr<<'\n';
                i+=1;
            }
            else if (str_list.at(i).contains("CACHEDEV_NAME=("))
            {
                QString tempStr=str_list.at(i+1);
                tempStr.replace(0, tempStr.length(),  m_cacheTaskInfo.m_blockInfo.m_name);
                stream<<tempStr<<'\n';
                i+=1;
            }
        }
    }

    write_file.close();
}

void CacheTaskParamsSetDialog::on_pushButton_cancel_clicked()
{
    hide();
}

void CacheTaskParamsSetDialog::on_comboBox_disks_currentIndexChanged(int index)
{
    int32 list_index = ui->comboBox_disks->currentData(Qt::UserRole).toUInt();
    m_diskSelected = m_pDiskList->at(list_index);

    ui->label_diskSize->setText(m_diskSelected.m_size);
}
